package com.atbun.aclservice.service.impl;

import com.atbun.aclservice.entity.AclUser;
import com.atbun.aclservice.service.PermissionService;
import com.atbun.aclservice.service.UserService;
import com.atbun.serurity.entity.SecurityUser;
import com.atbun.serurity.entity.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description : 用户认证详情
 * 实现UserDetailsService接口，在springsecurity配置中，使用面向接口开发的原则，会使用这个类
 * @Author : mayp
 * @Date: 2020-05-27 16:16
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;
    /**
     * 根据账户获取用户信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
//        数据库中取出用户信息
        AclUser user = userService.selectByUsername(username);
        if (null == user){
            throw new UsernameNotFoundException("用户名不存在!");
        }
        User curUser = new User(); //security中的用户类
        BeanUtils.copyProperties(user,curUser);

//        根据用户id查询权限
        List<String> authorities = permissionService.selectPermissionValueByUserId(user.getId());
        SecurityUser security = new SecurityUser(curUser);
        security.setPermissionValueList(authorities);
        return security;
    }
}
